package com.minelx.woods.task.core.sql.appender;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.minelx.sqlstructures.common.Files;
import com.minelx.woods.task.core.values.FieldPathValues;

public class AppenderFactory {
	private final JSONObject mappings;

	public AppenderFactory() {
		mappings = JSON.parseObject(Files.toString("/collections.json"));
	}

	// FIXME 2021/9/6  THIS METHOD NEEDED TEST SUPPORT!
	public CollectionAppender createAppender(JSONObject commitment) {
		String fieldName = commitment.getString("name");
		if (!mappings.containsKey(fieldName)) {
			throw new IllegalArgumentException("unknown fieldName: " + fieldName);
		}
		JSONObject rawMapping = mappings.getJSONObject(fieldName);
		if (rawMapping.containsKey("fieldPath")) { // simple field
			String[] fieldPath = rawMapping.getString("fieldPath").split("\\.");
			FieldPathValues result = new FieldPathValues(fieldPath[0], fieldPath[1], rawMapping.getString("alias"));
			return CollectionAppender.fromPathValues(result);
		} else if (rawMapping.containsKey("content") && commitment.containsKey("variables")) {
			return new ContentWithVariablesAppender(rawMapping, commitment.getJSONObject("variables"));
		} else if (rawMapping.containsKey("content")) { // child sql with content
			return new ContentAppender(rawMapping.getString("content"));
		} else {
			throw new IllegalArgumentException("unknown mapping: " + rawMapping);
		}
	}
}
